package com.android.lovely.ui.dialog

import android.content.DialogInterface
import android.os.SystemClock
import androidx.core.os.bundleOf
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.android.lovely.R
import com.android.lovely.const.StartCreateLoad
import com.android.lovely.databinding.DialogGenerateRoleBinding
import com.android.lovely.framework.BaseDialogFragment
import com.android.lovely.ui.viewmodel.CreateRoleViewModel
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.post
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

/**
 *
 * @author why
 * @date 2025/4/9 01:51
 */
class GenerateRoleDialog: BaseDialogFragment<DialogGenerateRoleBinding>() {

    private var isRegular = false

    private val viewModel by activityViewModels<CreateRoleViewModel>()

    override fun initializeViews() {
        viewLifecycleScope.launchSafety {
            viewModel.smartResponseFlow.collectLatest {
                isRegular = true
                dismissAllowingStateLoss()
            }
        }
        dialog?.setCanceledOnTouchOutside(false)
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        if (!isRegular) {
            requireActivity().showLovelyDialog {
                setDialogTitle(getString(R.string.dismiss_role_create))
                setNegativeButton (getString(R.string.btn_terminate)){
                    viewModel.smartCancel()
                }
                setPositiveButton(getString(R.string.btn_continue)) {
                    dismiss()
                    FlowBus.post(StartCreateLoad())
                }
            }
            viewModel.smartResponseFlow.onEach { dismissAllowingStateLoss() }.catch { }.launchIn(viewLifecycleScope)

        }
    }
}